'use client';

import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Button,
  Input,
  Select,
  Tag,
  Modal,
  Form,
  Popconfirm,
  message,
  Typography,
  Divider,
  Row,
  Col,
  Space,
  Checkbox,
  Statistic,
  Upload
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { 
  SearchOutlined, 
  EditOutlined, 
  DeleteOutlined, 
  CheckCircleOutlined, 
  CloseCircleOutlined, 
  FilterOutlined, 
  PlusOutlined,
  UploadOutlined
} from '@ant-design/icons';
import { sensitiveWordService, type SensitiveWord } from '@/service/sensitive-word.service';

const { Title, Text, Paragraph } = Typography;
const { Search } = Input;
const { Option } = Select;

// 敏感词状态定义
const WORD_STATUS = {
  ACTIVE: 1,
  INACTIVE: 0
};

// 敏感词状态映射
const statusMap: Record<number, { label: string; color: string }> = {
  [WORD_STATUS.ACTIVE]: { label: '启用', color: 'green' },
  [WORD_STATUS.INACTIVE]: { label: '禁用', color: 'red' }
};

const SensitiveWordManagement: React.FC = () => {
  // 状态定义
  const [words, setWords] = useState<SensitiveWord[]>([]);
  const [filteredWords, setFilteredWords] = useState<SensitiveWord[]>([]);
  const [selectedWords, setSelectedWords] = useState<number[]>([]);
  const [loading, setLoading] = useState(false);
  const [currentWord, setCurrentWord] = useState<SensitiveWord | null>(null);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isBatchModalVisible, setIsBatchModalVisible] = useState(false);
  const [searchText, setSearchText] = useState('');
  const [selectedStatus, setSelectedStatus] = useState<string>('all');
  
  const [wordForm] = Form.useForm();
  const [batchForm] = Form.useForm();

  // 分页状态
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });

  // 获取敏感词列表
  const fetchWords = async (page: number = pagination.current, pageSize: number = pagination.pageSize) => {
    setLoading(true);
    try {
      const response = await sensitiveWordService.getAllSensitiveWords();
      
      // 转换为前端需要的格式
      const wordsData = response.map(word => ({
        ...word
      }));
      
      // 应用搜索和状态筛选
      let filtered = wordsData;
      
      // 搜索筛选
      if (searchText) {
        filtered = filtered.filter(word => 
          word.word.toLowerCase().includes(searchText.toLowerCase())
        );
      }
      
      // 状态筛选
      if (selectedStatus !== 'all') {
        filtered = filtered.filter(word => 
          word.isActive === parseInt(selectedStatus)
        );
      }
      
      setWords(wordsData);
      setFilteredWords(filtered);
      
      // 更新分页信息
      setPagination({
        current: 1,
        pageSize: pageSize,
        total: filtered.length
      });
    } catch (error) {
      console.error('获取敏感词列表失败:', error);
      message.error('获取敏感词列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchWords();
  }, []);

  // 筛选敏感词 - 当筛选条件变化时重新加载
  useEffect(() => {
    fetchWords(1); // 重置到第1页
  }, [searchText, selectedStatus]);

  // 处理搜索
  const handleSearch = (value: string) => {
    setSearchText(value);
  };

  // 处理添加敏感词
  const handleAddWord = () => {
    setCurrentWord(null);
    wordForm.resetFields();
    setIsModalVisible(true);
  };

  // 处理编辑敏感词
  const handleEditWord = (word: SensitiveWord) => {
    setCurrentWord(word);
    wordForm.setFieldsValue({
      word: word.word
    });
    setIsModalVisible(true);
  };

  // 处理保存敏感词
  const handleSaveWord = async () => {
    try {
      const values = await wordForm.validateFields();
      if (currentWord) {
        // 更新敏感词
        await sensitiveWordService.updateSensitiveWord(currentWord.id, values.word);
        message.success('敏感词更新成功');
      } else {
        // 创建敏感词
        await sensitiveWordService.createSensitiveWord(values.word);
        message.success('敏感词添加成功');
      }
      setIsModalVisible(false);
      wordForm.resetFields();
      setCurrentWord(null);
      fetchWords();
    } catch (error: any) {
      console.error('保存敏感词失败:', error);
      message.error(error?.message || '保存敏感词失败');
    }
  };

  // 处理启用/禁用敏感词
  const handleToggleWordStatus = async (id: number, currentStatus: number) => {
    try {
      // 切换状态：0->1(启用), 1->0(禁用)
      const newStatus = currentStatus === WORD_STATUS.ACTIVE ? WORD_STATUS.INACTIVE : WORD_STATUS.ACTIVE;
      await sensitiveWordService.updateSensitiveWordStatus(id, newStatus);
      message.success(newStatus === WORD_STATUS.ACTIVE ? '敏感词已启用' : '敏感词已禁用');
      fetchWords();
    } catch (error: any) {
      console.error('操作敏感词失败:', error);
      message.error(error?.message || '操作敏感词失败');
    }
  };

  // 处理删除敏感词
  const handleDeleteWord = async (id: number) => {
    try {
      await sensitiveWordService.deleteSensitiveWord(id);
      message.success('敏感词删除成功');
      fetchWords();
    } catch (error: any) {
      console.error('删除敏感词失败:', error);
      message.error(error?.message || '删除敏感词失败');
    }
  };

  // 处理批量操作
  const handleBatchAction = async (action: string) => {
    if (selectedWords.length === 0) {
      message.warning('请先选择要操作的敏感词');
      return;
    }
    
    Modal.confirm({
      title: `确认${action === 'delete' ? '删除' : action === 'enable' ? '启用' : '禁用'}`,
      content: `确定要${action === 'delete' ? '删除' : action === 'enable' ? '启用' : '禁用'}选中的 ${selectedWords.length} 个敏感词吗？`,
      onOk: async () => {
        try {
          if (action === 'delete') {
            // 批量删除
            await sensitiveWordService.deleteSensitiveWordsBatch(selectedWords);
            message.success(`成功删除 ${selectedWords.length} 个敏感词`);
          } else if (action === 'enable') {
            // 批量启用
            for (const id of selectedWords) {
              await sensitiveWordService.updateSensitiveWordStatus(id, WORD_STATUS.ACTIVE);
            }
            message.success(`成功启用 ${selectedWords.length} 个敏感词`);
          } else if (action === 'disable') {
            // 批量禁用
            for (const id of selectedWords) {
              await sensitiveWordService.updateSensitiveWordStatus(id, WORD_STATUS.INACTIVE);
            }
            message.success(`成功禁用 ${selectedWords.length} 个敏感词`);
          }
          
          setSelectedWords([]);
          fetchWords();
        } catch (error: any) {
          console.error('批量操作失败:', error);
          message.error(error?.message || '批量操作失败');
        }
      }
    });
  };

  // 处理批量添加
  const handleBatchAdd = () => {
    batchForm.resetFields();
    setIsBatchModalVisible(true);
  };

  // 处理保存批量添加
  const handleSaveBatchAdd = async () => {
    try {
      const values = await batchForm.validateFields();
      const wordsArray = values.words.split(/[,，\n\s]+/).filter((word: string) => word.trim() !== '');
      
      if (wordsArray.length === 0) {
        message.warning('请输入至少一个敏感词');
        return;
      }
      
      await sensitiveWordService.createSensitiveWordsBatch(wordsArray);
      message.success(`成功添加 ${wordsArray.length} 个敏感词`);
      setIsBatchModalVisible(false);
      batchForm.resetFields();
      fetchWords();
    } catch (error: any) {
      console.error('批量添加敏感词失败:', error);
      message.error(error?.message || '批量添加敏感词失败');
    }
  };

  // 计算统计数据
  const totalWords = words.length;
  const activeWords = words.filter(word => word.isActive === WORD_STATUS.ACTIVE).length;
  const inactiveWords = words.filter(word => word.isActive === WORD_STATUS.INACTIVE).length;

  // 敏感词列表列配置
  const columns: ColumnsType<SensitiveWord> = [
    {
      title: (
        <Checkbox
          checked={selectedWords.length === filteredWords.length && filteredWords.length > 0}
          indeterminate={selectedWords.length > 0 && selectedWords.length < filteredWords.length}
          onChange={(e) => {
            if (e.target.checked) {
              setSelectedWords(filteredWords.map(word => word.id));
            } else {
              setSelectedWords([]);
            }
          }}
        />
      ),
      key: 'selection',
      width: 40,
      render: (_, record) => (
        <Checkbox
          checked={selectedWords.includes(record.id)}
          onChange={(e) => {
            if (e.target.checked) {
              setSelectedWords([...selectedWords, record.id]);
            } else {
              setSelectedWords(selectedWords.filter(id => id !== record.id));
            }
          }}
        />
      )
    },
    {
      title: '敏感词',
      dataIndex: 'word',
      key: 'word',
      width: 200
    },
    {
      title: '使用次数',
      dataIndex: 'usageCount',
      key: 'usageCount',
      width: 100,
      sorter: (a, b) => a.usageCount - b.usageCount,
    },
    {
      title: '状态',
      dataIndex: 'isActive',
      key: 'isActive',
      width: 100,
      render: (isActive: number) => (
        <Tag color={statusMap[isActive]?.color}>
          {statusMap[isActive]?.label}
        </Tag>
      )
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 180,
      render: (time: string) => new Date(time).toLocaleString()
    },
    {
      title: '更新时间',
      dataIndex: 'updatedAt',
      key: 'updatedAt',
      width: 180,
      render: (time: string) => new Date(time).toLocaleString()
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_, record: SensitiveWord) => (
        <Space size="middle">
          <Button size="small" icon={<EditOutlined />} onClick={() => handleEditWord(record)}>
            编辑
          </Button>
          <Button 
            size="small" 
            onClick={() => handleToggleWordStatus(record.id, record.isActive)}
            type={record.isActive === WORD_STATUS.ACTIVE ? 'default' : 'primary'}
          >
            {record.isActive === WORD_STATUS.ACTIVE ? '禁用' : '启用'}
          </Button>
          <Popconfirm
            title="确定要删除此敏感词吗?"
            onConfirm={() => handleDeleteWord(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button size="small" danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      )
    }
  ];

  return (
    <div style={{ padding: '20px' }}>
      <Title level={3}>敏感词管理</Title>
      
      {/* 批量操作栏 */}
      <Card style={{ marginBottom: '16px' }}>
        <Space>
          <Text>已选择 {selectedWords.length} 个敏感词</Text>
          <Button onClick={() => handleBatchAction('enable')} disabled={selectedWords.length === 0}>
            批量启用
          </Button>
          <Button onClick={() => handleBatchAction('disable')} disabled={selectedWords.length === 0}>
            批量禁用
          </Button>
          <Button danger onClick={() => handleBatchAction('delete')} disabled={selectedWords.length === 0}>
            批量删除
          </Button>
        </Space>
      </Card>
      
      <Row gutter={16} style={{ marginBottom: '24px' }}>
        {/* 敏感词统计卡片 */}
        <Col span={6}>
          <Card title="敏感词统计概览" bordered={true}>
            <div style={{ marginBottom: '16px' }}>
              <Statistic title="总敏感词数" value={totalWords} suffix="个" />
            </div>
            <div style={{ marginBottom: '16px' }}>
              <Statistic title="启用" value={activeWords} suffix="个" valueStyle={{ color: '#52c41a' }} />
            </div>
            <div style={{ marginBottom: '16px' }}>
              <Statistic title="禁用" value={inactiveWords} suffix="个" valueStyle={{ color: '#ff4d4f' }} />
            </div>
            
            <Divider style={{ margin: '16px 0' }} />
            
            <Button 
              type="primary" 
              icon={<PlusOutlined />} 
              onClick={handleAddWord}
              style={{ width: '100%', marginBottom: '8px' }}
            >
              添加敏感词
            </Button>
            <Button 
              icon={<UploadOutlined />} 
              onClick={handleBatchAdd}
              style={{ width: '100%' }}
            >
              批量添加
            </Button>
          </Card>
        </Col>
        
        {/* 敏感词列表 */}
        <Col span={18}>
          {/* 筛选工具栏 */}
          <Card style={{ marginBottom: '16px' }}>
            <Row gutter={[16, 16]}>
              <Col span={12}>
                <Search
                  placeholder="搜索敏感词"
                  allowClear
                  onSearch={handleSearch}
                  enterButton
                />
              </Col>
              <Col span={12}>
                <Select
                  placeholder="状态筛选"
                  value={selectedStatus}
                  onChange={setSelectedStatus}
                  style={{ width: '100%' }}
                  allowClear
                >
                  <Option value="all">全部状态</Option>
                  <Option value={WORD_STATUS.ACTIVE.toString()}>启用</Option>
                  <Option value={WORD_STATUS.INACTIVE.toString()}>禁用</Option>
                </Select>
              </Col>
            </Row>
          </Card>
          
          <Card title="敏感词列表">
            <Table
              columns={columns}
              dataSource={filteredWords}
              rowKey="id"
              loading={loading}
              pagination={{
                current: pagination.current,
                pageSize: pagination.pageSize,
                total: pagination.total,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total) => `共 ${total} 条记录`,
                onChange: (page, pageSize) => {
                  setPagination({ ...pagination, current: page, pageSize });
                },
                onShowSizeChange: (current, size) => {
                  setPagination({ ...pagination, pageSize: size });
                }
              }}
              scroll={{ x: 1200 }}
            />
          </Card>
        </Col>
      </Row>

      {/* 添加/编辑敏感词模态框 */}
      <Modal
        title={currentWord ? "编辑敏感词" : "添加敏感词"}
        open={isModalVisible}
        onOk={handleSaveWord}
        onCancel={() => {
          setIsModalVisible(false);
          wordForm.resetFields();
          setCurrentWord(null);
        }}
        okText="保存"
        cancelText="取消"
        width={600}
      >
        <Form form={wordForm} layout="vertical">
          <Form.Item
            label="敏感词"
            name="word"
            rules={[
              { required: true, message: '请输入敏感词' },
              { min: 1, max: 50, message: '敏感词长度应在 1-50 个字符之间' }
            ]}
          >
            <Input placeholder="请输入敏感词" />
          </Form.Item>
        </Form>
      </Modal>

      {/* 批量添加敏感词模态框 */}
      <Modal
        title="批量添加敏感词"
        open={isBatchModalVisible}
        onOk={handleSaveBatchAdd}
        onCancel={() => {
          setIsBatchModalVisible(false);
          batchForm.resetFields();
        }}
        okText="添加"
        cancelText="取消"
        width={600}
      >
        <Form form={batchForm} layout="vertical">
          <Form.Item
            label="敏感词列表"
            name="words"
            rules={[{ required: true, message: '请输入敏感词，多个敏感词用逗号、空格或换行分隔' }]}
          >
            <Input.TextArea 
              placeholder="请输入敏感词，多个敏感词用逗号、空格或换行分隔&#10;例如：垃圾,广告,spam&#10;或者：&#10;垃圾&#10;广告&#10;spam" 
              rows={6} 
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default SensitiveWordManagement;